package com.btjava.maven.pomver.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public class HTTPTools {

    public static final String HTTP_CHARSET = "utf-8";

    private static Logger logger = LoggerFactory.getLogger(HTTPTools.class);

    public static String post(String url, Map<String, String> parameter, String charset){
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        if(parameter != null){
            Set<String> keys = parameter.keySet();
            keys.forEach(key -> {
                formparams.add(new BasicNameValuePair(key, parameter.get(key)));
            });
        }
        UrlEncodedFormEntity uefEntity = null;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, charset);
            httppost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, "UTF-8");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            logger.info("发送post请求失败：{}", e.getMessage());
        } catch (UnsupportedEncodingException e) {
            logger.info("发送post请求失败：{}", e.getMessage());
        } catch (IOException e) {
            logger.info("发送post请求失败：{}", e.getMessage());
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "未知错误";
    }

    public static String post(String url, String jsondata, String charset){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        StringEntity se = null;
        try {
            se = new StringEntity(jsondata, charset);
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null && response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity());
            }
        } catch (UnsupportedEncodingException e) {
            logger.info("发送post请求失败：{}", e.getMessage());
        } catch (ClientProtocolException e) {
            logger.info("发送post请求失败：{}", e.getMessage());
        } catch (IOException e) {
            logger.info("发送post请求失败：{}", e.getMessage());
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "未知错误";
    }

    public static String postIgnoreSSl(String url, Map<String, String> parameter, String charset){
        logger.info("调用postIgnoreSSl开始,parameter:{}",parameter);
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = null;
        try {
            httpclient =getIgnoeSSLClient();
        }catch (Exception e){
            logger.warn("请求连接异常:{}",e.getMessage());
            e.printStackTrace();
            return "创建连接异常";
        }
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        if(parameter != null){
            Set<String> keys = parameter.keySet();
            keys.forEach(key -> {
                formparams.add(new BasicNameValuePair(key, parameter.get(key)));
            });
        }
        UrlEncodedFormEntity uefEntity = null;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, charset);
            httppost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, "UTF-8");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            logger.info("发送post请求失败：{}", e.getMessage());
        } catch (UnsupportedEncodingException e) {
            logger.info("发送post请求失败：{}", e.getMessage());
        } catch (IOException e) {
            logger.info("发送post请求失败：{}", e.getMessage());
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "未知错误";
    }

    public static String postIgnoreSSl(String url, String parameter, String charset){
            if(StringUtils.isBlank(parameter)){
                return "参数不能为空";
            }
            Map<String, String> map = new HashMap<String, String>();
            JSONObject json = JSONObject.parseObject(parameter);
            Set<Map.Entry<String, Object>> jsonSet = json.entrySet();
            Iterator<Map.Entry<String, Object>> it = jsonSet.iterator();
            while(it.hasNext()){
                Map.Entry<String, Object> objectEntry = it.next();
                map.put(objectEntry.getKey(), Objects.nonNull(objectEntry.getValue()) ?(objectEntry.getValue() instanceof String ? objectEntry.getValue().toString() : JSONObject.toJSONString(objectEntry.getValue())):null);
            }
            if(Objects.isNull(map)){
                return "参数不能为空或参数格式不正确";
            }
           return  postIgnoreSSl(url,map,charset);
    }

    private static CloseableHttpClient getIgnoeSSLClient() throws Exception {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();
        //创建httpClient
        CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).
                setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        return client;
    }

}
